package com.tom.zx.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tom.zx.entity.Role;
import com.tom.zx.service.IRoleService;
import com.tom.zx.service.IUserRoleService;
import com.tom.zx.vo.DistributionVo;
import com.tom.zx.vo.ReturnDistributionVo;
import com.tom.zx.vo.RoleVo;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 角色 前端控制器
 *
 * @author 王妍
 * @since 2022-02-20
 */
@RestController
@RequestMapping("/zx/role")
@AllArgsConstructor
public class RoleController {

  private final IUserRoleService userRoleService;

  private final IRoleService roleService;

  /** 为角色分配Id */
  @PostMapping("/user/{userId}")
  public void configureMenuForRole(
      @PathVariable("userId") Long userId, @RequestBody DistributionVo distributionVo) {
    userRoleService.configureRoleForUser(userId, Arrays.asList(distributionVo.getIds()));
  }

  @GetMapping("/page")
  public Page<RoleVo> loadRoles(Page<RoleVo> roleVoPage, RoleVo roleVo) {
    return roleService.loadPage(roleVoPage, roleVo);
  }

  @GetMapping
  public List<Role> getRoleList() {
    return roleService.list();
  }

  @GetMapping("/user/{userId}")
  public ReturnDistributionVo<Role> getRoleDistribution(@PathVariable("userId") Long userId) {
    return roleService.getRoleDistribution(userId);
  }

  /** 为角色分配Id */
  @PostMapping("/menu/{menuId}")
  public void configureRoleForMenu(
      @PathVariable("menuId") Long menuId, @RequestBody DistributionVo menuIds) {
    roleService.configureRoleForMenu(menuId, Arrays.asList(menuIds.getIds()));
  }

  /**
   * 获取角色已经有的菜单和没有的菜单
   *
   * @param menuId 角色Id
   * @return 返回角色的菜单分配
   */
  @GetMapping("menu/{menuId}")
  public ReturnDistributionVo<Role> getMenuDistribution(@PathVariable("menuId") Long menuId) {
    return roleService.getRoleDistributionByMenuId(menuId);
  }

  @PostMapping
  public boolean save(@RequestBody Role role) {
    return roleService.saveOrUpdate(role);
  }

  @DeleteMapping
  public boolean delete(@RequestBody Long[] roleIds) {
    return roleService.removeBatchByIds(Arrays.asList(roleIds));
  }
}
